const path = require('path')
const { defineConfig } = require('@vue/cli-service')
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { AntDesignVueResolver } = require('unplugin-vue-components/resolvers')
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin')
const WebpackBar = require('webpackbar')
const BundleAnalyzerPlugin =
  require('webpack-bundle-analyzer').BundleAnalyzerPlugin // 打包后 体积分析
// const TerserPlugin = require('terser-webpack-plugin')

/**
 * 是否本地开发环境
 */
const isDev = process.env.NODE_ENV == 'development'
/**
 * 是否进行打包分析
 */
const isAnalyzer = process.env.ENABLE_ANALYZER === 'true'

const antdvResolverConfig = {
  importStyle: 'less',
}
module.exports = defineConfig({
  transpileDependencies: true,
  chainWebpack: config => {
    // 原svg规则覆盖了所有的svg图标，需要先将自己的svg排除，以应用新的sprite规则
    // src/assets/svg 是我们将要存放svg的目录
    const svgDir = `src/assets/svg`
    config.module
      .rule('svg')
      .exclude.add(path.join(__dirname, svgDir)) // 排除自定义svg目录
      .end()

    config.module
      .rule('icons') // 新规则
      .test(/\.svg$/)
      .include.add(path.join(__dirname, svgDir)) // 新规则应用于我们存放svg的目录
      .end()
      .use('svg-sprite-loader') // 用sprite-loader接卸
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]',
      })
      .end()

    config.plugin('speed-measure-webpack-plugin').use(SpeedMeasurePlugin).end()

    config.plugin('define').tap(definitions => {
      Object.assign(definitions[0], {
        __VUE_OPTIONS_API__: 'true',
        __VUE_PROD_DEVTOOLS__: 'false',
        __VUE_PROD_HYDRATION_MISMATCH_DETAILS__: 'false',
      })
      return definitions
    })

    config.plugin('speed-measure-webpack-plugin').use(SpeedMeasurePlugin).end()

    if (!isDev) {
      config.optimization.minimizer('terser').tap(args => {
        Object.assign(args[0].terserOptions.compress, {
          // 生产模式 console.log 去除
          // warnings: false , // 默认 false
          drop_console: true,
          drop_debugger: true, // 默认也是true
          pure_funcs: ['console.log'],
        })
        return args
      })
    }
  },
  configureWebpack: config => {
    config.plugins.push(
      AutoImport.default({
        include: [
          /\.[tj]sx?$/, // .ts, .tsx, .js, .jsx
          /\.vue$/,
          /\.vue\?vue/, // .vue
          /\.md$/, // .md
        ],
        imports: [
          // presets
          'vue',
        ],
        // Array of strings of regexes that contains imports meant to be filtered out.
        ignore: ['useMouse', 'useFetch'],

        dts: './src/auto-imports.d.ts',
        eslintrc: {
          enabled: true, // Default `false`
          filepath: './.eslintrc-auto-import.json', // Default `./.eslintrc-auto-import.json`
          globalsPropValue: true, // Default `true`, (true | false | 'readonly' | 'readable' | 'writable' | 'writeable')
        },
        resolvers: [AntDesignVueResolver(antdvResolverConfig)],
      })
    )
    config.plugins.push(
      Components.default({
        resolvers: [AntDesignVueResolver(antdvResolverConfig)],
        dts: './src/components.d.ts',
      })
    )
    config.plugins.push(
      new WebpackBar({
        // color: "#85d", // 默认green，进度条颜色支持HEX
        basic: false, // 默认true，启用一个简单的日志报告器
        profile: false, // 默认false，启用探查器。
      })
    )

    if (!isDev && isAnalyzer) {
      config.plugins.push(new BundleAnalyzerPlugin())
    }

    // 通过文件缓存，加快二次启动速度
    config.cache = {
      type: 'filesystem',
    }
  },
  css: {
    loaderOptions: {
      less: {
        lessOptions: {
          modifyVars: {
            // 定制ant design vue的主题
            // 'primary-color': '#1DA57A',
            // 'link-color': '#1DA57A',
            // 'border-radius-base': '2px',
          },
          javascriptEnabled: true,
        },
      },
    },
  },
  devServer: {
    host: 'localhost', // 启动服务器域名
    port: '3000', // 启动服务器端口号
    open: true, // 是否自动打开浏览器
    hot: true, // 开启HMR功能（只能用于开发环境，生产环境不需要了）
  },
})
